package com.pick.base.util;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;

/**
 * IP地址工具类
 * 用于获取客户端真实IP地址
 */
@Slf4j
public class IPUtil {

    /**
     * 获取客户端真实IP地址
     * 
     * @param request HttpServletRequest对象
     * @return 客户端IP地址
     */
    public static String getClientIP(HttpServletRequest request) {
        if (request == null) {
            return "unknown";
        }
        
        String ip = null;
        
        try {
            // 1. 检查X-Forwarded-For头
            ip = request.getHeader("X-Forwarded-For");
            if (isValidIP(ip)) {
                // X-Forwarded-For可能包含多个IP，取第一个
                if (ip.contains(",")) {
                    ip = ip.split(",")[0].trim();
                }
                return ip;
            }
            
            // 2. 检查X-Real-IP头
            ip = request.getHeader("X-Real-IP");
            if (isValidIP(ip)) {
                return ip;
            }
            
            // 3. 检查Proxy-Client-IP头
            ip = request.getHeader("Proxy-Client-IP");
            if (isValidIP(ip)) {
                return ip;
            }
            
            // 4. 检查WL-Proxy-Client-IP头
            ip = request.getHeader("WL-Proxy-Client-IP");
            if (isValidIP(ip)) {
                return ip;
            }
            
            // 5. 检查HTTP_CLIENT_IP头
            ip = request.getHeader("HTTP_CLIENT_IP");
            if (isValidIP(ip)) {
                return ip;
            }
            
            // 6. 检查HTTP_X_FORWARDED_FOR头
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            if (isValidIP(ip)) {
                return ip;
            }
            
            // 7. 最后使用getRemoteAddr()方法
            ip = request.getRemoteAddr();
            if (isValidIP(ip)) {
                return ip;
            }
            
        } catch (Exception e) {
            log.warn("获取客户端IP地址失败: {}", e.getMessage());
        }
        
        return "unknown";
    }
    
    /**
     * 验证IP地址是否有效
     * 
     * @param ip IP地址字符串
     * @return 是否有效
     */
    private static boolean isValidIP(String ip) {
        if (ip == null || ip.trim().isEmpty()) {
            return false;
        }
        
        ip = ip.trim();
        
        // 排除无效值
        if ("unknown".equalsIgnoreCase(ip) || 
            "localhost".equalsIgnoreCase(ip) ||
            ip.length() < 7) {
            return false;
        }
        
        return true;
    }
    
    /**
     * 判断是否为内网IP
     * 
     * @param ip IP地址
     * @return 是否为内网IP
     */
    public static boolean isInternalIP(String ip) {
        if (!isValidIP(ip)) {
            return false;
        }
        
        try {
            String[] parts = ip.split("\\.");
            if (parts.length != 4) {
                return false;
            }
            
            int first = Integer.parseInt(parts[0]);
            int second = Integer.parseInt(parts[1]);
            
            // 10.0.0.0 - 10.255.255.255
            if (first == 10) {
                return true;
            }
            
            // 172.16.0.0 - 172.31.255.255
            if (first == 172 && second >= 16 && second <= 31) {
                return true;
            }
            
            // 192.168.0.0 - 192.168.255.255
            if (first == 192 && second == 168) {
                return true;
            }
            
            // 127.0.0.0 - 127.255.255.255 (本地回环)
            if (first == 127) {
                return true;
            }
            
        } catch (NumberFormatException e) {
            log.warn("解析IP地址失败: {}", ip);
        }
        
        return false;
    }
    
    /**
     * 获取客户端IP地址的详细信息
     * 
     * @param request HttpServletRequest对象
     * @return IP地址信息
     */
    public static String getClientIPInfo(HttpServletRequest request) {
        if (request == null) {
            return "Request is null";
        }
        
        StringBuilder info = new StringBuilder();
        info.append("Client IP: ").append(getClientIP(request));
        
        // 添加所有相关的头信息
        String[] headers = {
            "X-Forwarded-For", "X-Real-IP", "Proxy-Client-IP", 
            "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR"
        };
        
        for (String header : headers) {
            String value = request.getHeader(header);
            if (value != null && !value.trim().isEmpty()) {
                info.append(", ").append(header).append(": ").append(value);
            }
        }
        
        info.append(", RemoteAddr: ").append(request.getRemoteAddr());
        
        return info.toString();
    }
}